document.addEventListener('DOMContentLoaded', function() {
    const productForm = document.getElementById('product-form');

    productForm.addEventListener('submit', async function(e) {
        e.preventDefault();

        // 获取表单数据
        const formData = new FormData();
        formData.append('name', document.getElementById('name').value);
        formData.append('price', document.getElementById('price').value);
        formData.append('originalPrice', document.getElementById('originalPrice').value);
        formData.append('categoryId', document.getElementById('categoryId').value);
        formData.append('stock', document.getElementById('stock').value);
        formData.append('status', document.getElementById('status').value);
        formData.append('description', document.getElementById('description').value);
        formData.append('tags', document.getElementById('tags').value);
        formData.append('location', document.getElementById('location').value);
        formData.append('attributes', document.getElementById('attributes').value);
        formData.append('expireTime', document.getElementById('expireTime').value);

        // 添加图片文件
        const imageFiles = document.getElementById('images').files;
        for (let i = 0; i < imageFiles.length; i++) {
            formData.append('images', imageFiles[i]);
        }

        try {
            // 使用API提交商品数据
            const response = await fetch('/api/products', {
                method: 'POST',
                body: formData,
                credentials: 'include'
            });

            if (!response.ok) {
                const error = await response.json();
                throw new Error(error.message || '发布商品失败');
            }

            const result = await response.json();
            alert('商品发布成功！');
            window.location.href = 'products.html';
        } catch (error) {
            console.error('发布商品错误:', error);
            alert(error.message);
        }
    });

    // 检查用户登录状态
    checkLoginStatus();
});

// 检查用户登录状态
function checkLoginStatus() {
    const authLink = document.getElementById('auth-link');
    const authText = document.getElementById('auth-text');
    const userAvatar = document.getElementById('user-avatar');

    // 从localStorage获取用户信息
    const user = JSON.parse(localStorage.getItem('user'));

    if (user) {
        authText.textContent = user.username;
        if (user.avatar) {
            userAvatar.src = user.avatar;
            userAvatar.style.display = 'inline';
        }
        authLink.href = 'user.html';
    } else {
        authText.textContent = '登录/注册';
        authLink.href = 'login.html';
    }
}